#pragma once

#include <map>
#include <set>
#include "GSE_Net.h"
#include "GSE_Log.h"
#include <windows.h>

using namespace GSE;

class CServer
{
public:
	CServer(void);
	~CServer(void);

	void Init();
	void Listen(const char * strIP,const char * strPort);
	void Uninit();
	void SetMgr(ISessionManager * lpMgr)
	{
		m_lpListener->SetSessionManager(lpMgr);
		m_lpMgr = lpMgr;
	}
	void Shutdown()
	{
		m_bShutdown = true;
	}
	void run()
	{
		while ( !m_bShutdown )
		{
			m_lpListener->Run();
			Sleep(1);
		}
	}
private:
	GSE::ISessionManager *	m_lpMgr;
	GSE::IListener *		m_lpListener;
	bool				m_bShutdown;
};


class CServerCallback_Test1 : public ISessionCallback
{
public:
	CServerCallback_Test1(ISession * lpSession):m_lpSession(lpSession){}

	virtual void OnReceive(const char * lpBuffer, uint32 uLen)
	{
		if ( memcmp(lpBuffer,"Bye",3) == 0)
		{
			m_lpSession->Send("Bye",3);
			return;
		}
		std::string t(lpBuffer,uLen);
		LOG(LOG_GSE_CRITICAL) << t.c_str();
	}
	virtual void OnConnected()
	{
		LOG(LOG_GSE_CRITICAL) << __FUNCTION__ ;
	}
	virtual void OnDisconnected()
	{
		LOG(LOG_GSE_CRITICAL) << __FUNCTION__ ;
	}

	virtual void OnError(int errCode,const char * errMsg)
	{
		LOG(LOG_GSE_CRITICAL) << errMsg;
	}


protected:
	ISession * m_lpSession;

};


class CServerSessionMgr_Test1: public ISessionManager
{
public:
	virtual void OnAccept(ISession * lpSession)
	{
		lpSession->SetCallback(new CServerCallback_Test1(lpSession));
		m_Sessions.insert(lpSession);
	}
	virtual void OnCloseSession(ISession * lpSession)
	{
		delete lpSession->GetCallbackPtr();
		m_Sessions.erase(lpSession);
	}
	virtual void Release()
	{
		delete this;
	}
protected:
	std::set<ISession *> m_Sessions;
};